package main

import (
	"github.com/julienschmidt/httprouter"
	"net/http"
	"video_server/api/session"
)

type middleWareHandler struct {
	r *httprouter.Router
}

func NewMiddleWareHandler(r *httprouter.Router) http.Handler{
	m :=middleWareHandler{}
	m.r = r
	return m
}

func(m middleWareHandler) ServeHTTP(w http.ResponseWriter,r *http.Request){
	validateUserSession(r)
	m.r.ServeHTTP(w,r)
}


func RegisterHandlers() *httprouter.Router  {
	router := httprouter.New()
	router.POST("/user",CreateUser)
	router.POST("/user/:username",Login)
	router.GET("/user/:username",GetUserInfo)
	router.POST("/user/:username/videos",AddNewVideo)
	router.GET("/user/:username/videos",ListAllVideos)
	router.DELETE("/user/:username/videos/:vid-id",DeleteVideo)
	router.POST("/videos/:vid-id/comments",PostComment)
	router.GET("/videos/:vid-id/comments",ShowComments)
	return router
}

func Prepare(){
	session.LoadSessionsFromDB()
}

func main()  {
	r := RegisterHandlers()
	mh := NewMiddleWareHandler(r)//自定义handler 劫持请求，做拦截处理
	http.ListenAndServe(":8000",mh)// 将main函数阻塞在这里；listen -> RegisterHandlers -> handlers
}





//handler -> validation{1. request,2.user} -> business logic ->response
//validation: 1.data model  2 error handling
// session